package com.study.hot.jetpack.viewmodel

import androidx.lifecycle.ViewModelProvider
import com.study.base.BaseActivity
import com.study.hot.R
import kotlinx.android.synthetic.main.activity_view_model.*
import org.jetbrains.anko.sdk27.coroutines.onClick

/**
 * <pre>
 *     author : fauks
 *     time   : 2020/03/24
 *     desc   : 用于保存Activity状态、数据，在Activity创建(横竖屏切换、系统语言切换)创建时数据不会丢失
 * </pre>
 */
class ViewModelActivity : BaseActivity() {
    override fun generateLayoutId() = R.layout.activity_view_model

    override fun initView() {
        useNormal()
        useViewModel()
    }

    /**
     * Activity意外重启不会丢失数据
     */
    lateinit var customViewModel: CustomViewModel
    private fun useViewModel() {
        //获取ViewModel
        customViewModel = ViewModelProvider(this)[CustomViewModel::class.java]
        viewModelNumTv.text = customViewModel.num.toString()
        addViewModelNumBtn.onClick {
            customViewModel.num++
            viewModelNumTv.text = customViewModel.num.toString()
        }
    }

    /**
     * 使用普通变量保存值在Activity意外重启值丢失
     */
    var num = 0
    private fun useNormal() {
        normalNumTv.text = num.toString()
        addNormalNumBtn.onClick {
            normalNumTv.text = num++.toString()
        }
    }
}